/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-11-18 23:15:21
 * @LastEditors: lhl
 * @LastEditTime: 2024-11-18 23:20:00
 */
import React, { useEffect, useState } from 'react';
import { Tabs } from 'antd';
import type { TabsProps } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAppSelector } from '@/hooks/store';
import './index.module.less';

interface TabItem {
  key: string;
  label: string;
  closable: boolean;
}

const TabsView: React.FC = () => {
  const [activeKey, setActiveKey] = useState<string>('');
  const [items, setItems] = useState<TabItem[]>([]);
  const location = useLocation();
  const navigate = useNavigate();
  const menuList = useAppSelector((state) => state.menu.menuList);

  useEffect(() => {
    addTab(location.pathname);
  }, [location.pathname]);

  const findMenuTitle = (path: string) => {
    const findInMenus = (menus: any[]): string | null => {
      for (const menu of menus) {
        if (menu.path === path) return menu.meta.title;
        if (menu.children) {
          const found = findInMenus(menu.children);
          if (found) return found;
        }
      }
      return null;
    };
    return findInMenus(menuList) || path;
  };

  const addTab = (path: string) => {
    const title = findMenuTitle(path);
    setActiveKey(path);

    setItems((prevItems) => {
      if (!prevItems.find((item) => item.key === path)) {
        return [
          ...prevItems,
          {
            key: path,
            label: title,
            closable: path !== '/dashboard',
          },
        ];
      }
      return prevItems;
    });
  };

  const onChange = (key: string) => {
    navigate(key);
  };

  const onEdit: TabsProps['onEdit'] = (targetKey, action) => {
    if (action === 'remove' && typeof targetKey === 'string') {
      setItems((prevItems) => {
        const newItems = prevItems.filter((item) => item.key !== targetKey);
        if (activeKey === targetKey) {
          const lastTab = newItems[newItems.length - 1];
          setActiveKey(lastTab.key);
          navigate(lastTab.key);
        }
        return newItems;
      });
    }
  };

  return <Tabs type="editable-card" onChange={onChange} activeKey={activeKey} onEdit={onEdit} items={items} />;
};

export default TabsView;
